package com.psp.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.northend.util.AppTextUtil;
import com.northend.util.NumUtil;
import com.northend.util.StringUtil;
import com.psp.web.controller.res.BaseResult;
import com.psp.web.controller.res.ListResult;
import com.psp.web.controller.res.ObjectResult;
import com.psp.web.controller.res.bean.RConfirmOrderBean;
import com.psp.web.controller.res.bean.RConfirmOrderProductBean;
import com.psp.web.controller.res.bean.ROrderDetailBean;
import com.psp.web.controller.res.bean.ROrderListBean;
import com.psp.web.controller.res.bean.RServiceBean;
import com.psp.web.controller.springmvc.req.GetConfirmOrderParam;
import com.psp.web.controller.springmvc.req.GetConfirmOrderProductParam;
import com.psp.web.controller.springmvc.req.GetOrderDetailParam;
import com.psp.web.controller.springmvc.req.GetOrderListParam;
import com.psp.web.controller.springmvc.req.GetPCBOrderParam;
import com.psp.web.controller.springmvc.req.GetServiceParam;
import com.psp.web.controller.springmvc.req.GetWechatQRCodeParam;
import com.psp.web.model.OrderBean;
import com.psp.web.service.OrderService;
import com.psp.web.service.ServiceService;
import com.psp.web.service.exception.ServiceException;
import com.psp.web.service.impl.PageResult;

@Controller
@RequestMapping(value = "/psp/order", produces = "application/json")
@Component
public class OrderController {
	
	Logger logger = Logger.getLogger(OrderController.class);

	@Autowired
	OrderService orderServiceImpl;

	@Autowired
	private ServiceService serviceServiceImpl;// 订单业务

	/**
	 * 获取订单详情
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public ObjectResult<ROrderDetailBean> getDetail(GetOrderDetailParam param, HttpServletRequest request,
			HttpServletResponse response) {
		ObjectResult<ROrderDetailBean> result = new ObjectResult<ROrderDetailBean>();
		String token = (String) request.getAttribute("token");
		try {
			String uid = (String) request.getAttribute("userId");
			String oid = param.getOid();
			ROrderDetailBean resBean = orderServiceImpl.getDetail(uid, oid);
			result.setData(resBean);
			result.setFlag(resBean != null);
		} catch (ServiceException e) {
			result.setServiceException(e);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setServiceException(new ServiceException("error", "发生异常"));
		}
		result.setToken(token);
		return result;
	}

	/**
	 * 获取订单列表
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public ListResult<ROrderListBean> list(GetOrderListParam param, HttpServletRequest request,
			HttpServletResponse response) {
		ListResult<ROrderListBean> result = new ListResult<>();
		String token = (String) request.getAttribute("token");
		try {

			String uid = (String) request.getAttribute("userId");
			int page = NumUtil.toInt(param.getPage(), 0);
			int pageSize = NumUtil.toInt(param.getPageSize(), 10);
			String orderNo = StringUtil.isEmpty(param.getOrderNo()) ? null : param.getOrderNo();
			Integer state = NumUtil.toInt(param.getState(), 0);// TODO:订单状态：1,2已下单，沟通报价
			int[] s = { state };
			if (state == 0) {
				s = null;
			}
			if (state == 1) {
				s = new int[] { 1, 2 };
			}
			PageResult<ROrderListBean> resList = orderServiceImpl.getList(page, pageSize, uid, orderNo, s);

			result.setData(resList.getData());
			result.setTotalSize(resList.getCount());
			result.setPage(page);
		} catch (ServiceException e) {
			result.setServiceException(e);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setServiceException(new ServiceException("error", "发生异常"));
		}
		result.setToken(token);
		return result;
	}

	/**
	 * 获取确认订单中的服务信息
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public ObjectResult<RConfirmOrderProductBean> getOrderProduct(GetConfirmOrderProductParam param,
			HttpServletRequest request, HttpServletResponse response) {
		ObjectResult<RConfirmOrderProductBean> result = new ObjectResult<>();
		String token = (String) request.getAttribute("token");
		try {
			String uid = (String) request.getAttribute("userId");
			String pid = param.getPid();
			String skuCode = param.getSkuCode();

			RConfirmOrderProductBean resdata = orderServiceImpl.getOrderProduct(uid, pid, skuCode);
			result.setFlag(resdata != null);
			result.setData(resdata);
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			result.setServiceException(e);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setServiceException(new ServiceException("error", "发生异常"));
		}
		result.setToken(token);
		return result;
	}

	/**
	 * 订单确认
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public ObjectResult<RConfirmOrderBean> confirmOrder(GetConfirmOrderParam param, HttpServletRequest request,
			HttpServletResponse response) {
		ObjectResult<RConfirmOrderBean> result = new ObjectResult<RConfirmOrderBean>();
		String token = (String) request.getAttribute("token");
		try {
			String uid = (String) request.getAttribute("userId");
			String pid = param.getPid();
			String skuCode = param.getSkuCode();
			String addressAid = param.getAddresseeAid();
			String invoiceHeaderId = param.getInvoiceHeaderId();
			String invoiceAid = param.getInvoiceAid();
			OrderBean resdata = orderServiceImpl.confirmOrder(uid, pid, skuCode, addressAid, invoiceHeaderId,
					invoiceAid);
			RConfirmOrderBean opb = new RConfirmOrderBean();
			opb.setOrderNo(resdata.getOrderNo());
			opb.setOrderId(resdata.getOid());
			result.setData(opb);
		} catch (ServiceException e) {
			result.setServiceException(e);
		}
		result.setToken(token);
		return result;
	}

	/**
	 * pcb下单
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public BaseResult pcbOrder(GetPCBOrderParam param, HttpServletRequest request, HttpServletResponse response) {
		BaseResult result = new BaseResult();
		try {
			StringBuilder sb = new StringBuilder();
			ServletInputStream input = request.getInputStream();
			byte[] read = new byte[1024];
			int len = -1;
			while ((len = input.read(read)) != -1) {
				sb.append(new String(read, 0, len));
			}
			logger.info("jieshou guolai de shuju :");
			logger.info(sb.toString());
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		return result;
	}

	/**
	 * 获取微信二维码
	 * 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 */
	public BaseResult getWechatQRCode(GetWechatQRCodeParam param, HttpServletRequest request,
			HttpServletResponse response) {
		BaseResult result = new BaseResult();
		OutputStream os = null;
		try {
			String uid = (String) request.getAttribute("userId");
			String oid = param.getOid();
			String pid = param.getPid();
			String attach = param.getAttach();
			String body = param.getBody();
			String detail = param.getDetail();
			Integer totalFee = NumUtil.toInt(param.getTotalFee(), 1);// 1分
			Integer width = NumUtil.toInt(param.getWidth(), 300);//
			os = response.getOutputStream();
			response.setContentType("image/*"); // 设置返回的文件类型
			String ip = AppTextUtil.getIpAddr(request);
			orderServiceImpl.getWechatQRCode(uid, pid, attach, body, detail, totalFee, os, width, ip, oid);
			os.flush();
		} catch (ServiceException e) {
			result.setServiceException(e);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 支付回调
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public BaseResult payBack(HttpServletRequest request, HttpServletResponse response) {
		BaseResult result = new BaseResult();
		try {
			boolean flag = orderServiceImpl.updatePayedOrder(request, response);
			result.setFlag(flag);
		} catch (ServiceException e) {
			result.setServiceException(e);
		} catch (Exception e) {
			result.setFlag(false);
			result.setMsg(e.getMessage());
		}
		return result;
	}
	
	/**
	 * 服务列表
	 **/
	@RequestMapping("/v1/serviceList")
	@ResponseBody
	public ListResult<RServiceBean> getServices(GetServiceParam param, HttpServletRequest request,
			HttpServletResponse response) {
		ListResult<RServiceBean> result = new ListResult<>();
		try {
			int page = NumUtil.toInt(param.getPage(), 0);
			int limit = NumUtil.toInt(param.getLimit(), 20);
			int count = serviceServiceImpl.getTotalCount();
			if (count > 0) {
				List<RServiceBean> data = serviceServiceImpl.getServiceList(page, limit);
				data.sort(new Comparator<RServiceBean>() {

					@Override
					public int compare(RServiceBean o1, RServiceBean o2) {
						int code = new Random().nextInt(3) - 2;
						return code;
					}

				});
				result.setData(data);
				result.setFlag(data != null);
				result.setTotalSize(count);
			}
			result.setPage(page);

		} catch (ServiceException e) {
			result.setServiceException(e);
		}
		return result;
	}

}
